<?php namespace App\Http\Controllers\Api;


use App\Files;
use App\Http\Controllers\Controller;
use App\Images;
use App\Http\Services\FileManager;
use App\User;
use App\UserInfo;
use App\VideoImgs;
use App\Videos;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;


/**
 * Created by PhpStorm.
 * User: liandne
 * Date: 2016/12/9
 * Time: 下午4:00
 */

class ImageController extends Controller
{

    /**
     * @param Guard $guard
     * @param Request $request
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function upload(Request $request)
    {
        $uploadFile = $request->file('photo');

        if (!$request->hasFile('photo'))
            return response()->json(['level'=>'error','message'=>'文件不存在！']);

        if (!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'上传失败！']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile, $fileName,"oss2");

        $imageModel = new Images();
        $imageModel->file_id = $fileModel->id;
        $imageModel->img_name = $fileName;
        $imageModel->img_type = $fileModel->file_type;
        $imageModel->save();

        $imageModel->img_url = FileManager::getImgFromOssUrl($imageModel->id);

        return response()->json(['level'=>'success','message'=>'上传成功！','data'=>$imageModel]);
    }

    /**
     * @param Guard $guard
     * @param Request $request
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function uploadVideo(Request $request)
    {
        $uploadFile = $request->file('video');

        if(!$request->hasFile('video'))
            return response()->json(['level'=>'error','message' => '文件不存在！'], 203);

        if(!$uploadFile->isValid())
            return response()->json(['level'=>'error','message' => '上传失败'], 203);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::upLoadFile($uploadFile,$fileName,'oss2','video');

        $thatVideo = null;
        $thatVideo = Videos::whereFileId($fileModel->id)->first();
        if(!$thatVideo){
            $thatVideo = new Videos();
            $thatVideo->file_id    = $fileModel->id;
            $thatVideo->video_name = $fileName;
            $thatVideo->video_type = $fileModel->file_type;
            $thatVideo->key        = $fileModel->file_md5;
            $thatVideo->save();
        }

        $thatVideo->video_url = FileManager::getVideoFromOssUrl($thatVideo->id);

        return response()->json(['level'=>'success','message'=>'上传成功！','data'=>$thatVideo]);
    }

    /**
     * @param Guard $guard
     * @param Request $request
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function uploadVideoImg(Request $request)
    {
        $uploadFile = $request->file('photo');

        if (!$request->hasFile('photo'))
            return response()->json(['level'=>'error','message'=>'文件不存在！']);

        if (!$uploadFile->isValid())
            return response()->json(['level'=>'error','message'=>'上传失败！']);

        $fileName = $uploadFile->getClientOriginalName();

        /** @var Files $fileModel */
        $fileModel = FileManager::UploadFile($uploadFile, $fileName,"oss2");

        /** @var VideoImgs $thatImages */
        $thatImages = VideoImgs::whereFileMd5($fileModel->file_md5)->first();
        if(!$thatImages){

            $otherActive = VideoImgs::whereIsActive(1)->first();
            if($otherActive){
                $otherActive->is_active = 0;
                $otherActive->save();
            }

            $thatImages = new VideoImgs();
            $thatImages->file_id = $fileModel->id;
            $thatImages->img_name = $fileName;
            $thatImages->img_type = $fileModel->file_type;
            $thatImages->file_md5 = $fileModel->file_md5;
            $thatImages->is_active = 1;
            $thatImages->save();
        }else{
            $otherActive = VideoImgs::whereIsActive(1)->first();
            if($otherActive && $otherActive->id != $thatImages->id){
                $otherActive->is_active = 0;
                $otherActive->save();
            }else if(!$otherActive) {
                $thatImages->is_active = 1;
                $thatImages->save();
            }
        }

        $thatImages->img_url = FileManager::getVideoImgFromOssUrl($thatImages->id);

        return response()->json(['level'=>'success','message'=>'上传成功！','data'=>$thatImages]);
    }

    public function showPhotoByUserid($id=0){
        /** @var UserInfo $thatUserInfo */
        $thatUserInfo = UserInfo::whereUserId($id)->first();
        if(!$thatUserInfo){
            return \Response::download('images/default_avatar.png','default_img.png',[],'inline');
        }

        if($thatUserInfo->photo_id == 0){
            return \Response::download('images/default_avatar.png','default_img.png',[],'inline');
        }

        /** @var Images $images */
        $images = Images::whereId($thatUserInfo->photo_id)->first();
        if(!$images)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        $imageFile = $images->files;
        if(!$imageFile || $imageFile == null)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        return \Response::download($imageFile->getLocalPath(),$imageFile->img_name,[],'inline');
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function getImageUrlById($id=0){
        if(is_null($id))
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        if(is_numeric($id) && $id == 0)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        /** @var Images $images */
        $images = Images::find($id);

        if(!$images)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        $imageFile = $images->files;
        if(!$imageFile || $imageFile == null)
            return \Response::download('images/default_img.png','default_img.png',[],'inline');

        return \Response::download($imageFile->getLocalPath(),$imageFile->img_name,[],'inline');
    }

    public function getImageBinAsShowById($id, $size = null)
    {
        $image = Images::whereId($id)->first();
        $file = null;
        if (!$image)
            return \Response::download('src/images/image_default.jpg', 'image_default.jpg', [], 'inline');

        switch ($size) {
            case '1000px':
                if ($image->file1000px)
                    $file = $image->file1000px;
                break;
            case '300px':
                if ($image->file300px)
                    $file = $image->file300px;
                break;
            case '100px':
                if ($image->file100px)
                    $file = $image->file100px;
                break;
            default:
                if ($image->file)
                    $file = $image->file;
                break;
        }
        if (!$file)
            return \Response::download('src/images/image_default.jpg', 'image_default.jpg', [], 'inline');

        return \Response::download($file->getLocalPath(), $file->file_name, [], 'inline');
    }

    /**
     * 截取图片接口
     * @param Guard $guard
     * @param CropImageRequest $request
     * @throws DataException
     * @throws SecurityException
     */
    public function CropImage(Guard $guard, CropImageRequest $request)
    {

        $width = $request->get('width');
        $height = $request->get('height');
        $cropx = $request->get('cropx');
        $cropy = $request->get('cropy');
        $img_id = $request->get('image_id');

        $imageData = Images::find($img_id);
        if (!$imageData)
            throw new DataException(DataException::NotExistError);
        $file = $imageData->files;
        if (!$file)
            throw new DataException(DataException::NotExistError);

        $file_path = $file->getLocalPath();

        $img = Image::make($file_path);
        $new = storage_path() . '/app/' . $file->file_url . '/' . explode($file->file_type, $file->file_name)[0] . ' Cut' . $file->file_type;
        $name = explode($file->file_type, $file->file_name)[0] . ' Cut' . $file->file_type;
        $img->crop($width, $height, intval($cropx), intval($cropy))->save($new);

        $files = FileManager::uploadCropFile($new, $img->getEncoded(), $name, $file->file_type);

        $imageModel = Images::whereFileId($files->id)->first();
        if (!$imageModel) {
            $imageModel = new Images();
            $imageModel->file_id = $files->id;
            $imageModel->img_name = $files->file_name;
            $imageModel->img_type = $files->file_type;
            $imageModel->save();
        }

        return $this->buildResponse(trans('裁剪图片成功'), array('crop_image_id' => $imageModel->id));
    }

    /**
     * 多图片上传
     * @param Guard $guard
     *
     * @return Response|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws FileUploadException
     * @throws SecurityException
     */
    public function uploadImages(Guard $guard)
    {
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var  Validator $validator */
        $validator = Validator::make($this->request->all(), [
            'photo' => 'required|array',
        ]);
        if ($validator->fails())
            return (new Response($validator->messages()->toArray(), 422));
        $files = $this->request->file('photo');

        foreach ($files as $key => $val) {
            /** @var UploadedFile $val */
            $size = 1024 * 3;
            $validator = Validator::make($files, [
                $key => 'required|mimes:jpeg,bmp,png,gif|image|between:1,' . $size
            ]);
            if ($validator->fails()) {
                $validator->errors()->add($key, '图片');
                return (new Response($validator->messages()->toArray(), 422));
            }
            /** @var UploadedFile $val */
            if (!$val->isValid())
                throw new FileUploadException(FileUploadException::UploadFailWithError);
        }

        $images = DB::transaction(function () use ($files) {
            foreach ($files as $value) {
                /** @var UploadedFile $value */
                $fileName = $value->getClientOriginalName();

                /** @var Files $fileModel */
                $fileModel = FileManager::UploadFile($value, $fileName);
                /** @var Images $imageModel */
                $images[] = FileManager::buildImageMultipx($fileModel);
            }
            return $images;
        });
        return $this->buildResponse(trans('图片上传成功'), $images);

    }
}